package com.vken.blog.dao.hibernate;

import java.util.List;

import com.vken.blog.dao.EntryDao;
import com.vken.blog.model.Entry;
import com.vken.blog.util.Pagination;

public class EntryDaoHibernate extends GenericDaoHibernate<Entry, Integer> implements EntryDao {
	public Pagination getPaginationByBlogId(Integer id, Integer status, int pageSize, int pageNumber) {
		StringBuffer sb = new StringBuffer();
		sb.append("from Entry as e where e.category.blog.id=");
		sb.append(id);
		if (status != null) {
			sb.append(" and e.status=");
			sb.append(status);
		}

		int totalCount = ((Long) queryObject("select count(*) " + sb.toString(), null)).intValue();
		return getPagination(sb.toString() + " order by e.id desc", null, pageSize, pageNumber,
				totalCount);
	}

	public Pagination getPaginationByCategoryId(Integer id, Integer status, int pageSize,
			int pageNumber) {
		StringBuffer sb = new StringBuffer();
		sb.append("from Entry as e where e.category.id=");
		sb.append(id);
		if (status != null) {
			sb.append(" and e.status=");
			sb.append(status);
		}

		int totalCount = ((Long) queryObject("select count(*) " + sb.toString(), null)).intValue();
		return getPagination(sb.toString() + " order by e.id desc", null, pageSize, pageNumber,
				totalCount);
	}

	public void updateCommentHit(final Integer id) {
		String hql = "select count(*) from Comment as c where status=1 and c.entry.id=" + id;
		final int totalCount = ((Long) queryObject(hql, null)).intValue();
		Entry e = findById(id);
		e.setCommentHit(totalCount);
		update(e);
	}

	public List<Entry> getEntrysByCategoryId(Integer categoryId) {
		String hql = "from Entry as e where e.category.id=" + categoryId;
		return getHibernateTemplate().find(hql);
	}
}
